package com.xiran.todoself.service;

import com.xiran.todoself.common.Response;
import com.xiran.todoself.mapper.UserMapper;
import com.xiran.todoself.model.dto.LoginDto;
import com.xiran.todoself.model.pojo.User;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class UserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private PasswordEncoder passwordEncoder;

    // 修改密码/用户信息
    public void change(LoginDto dto) {
        // 优化：一次查询即可
        User user = userMapper.findByUsername(dto.getUsername());
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        // 仅在密码不为空时更新密码（避免覆盖为空）
        if (dto.getPassword() != null && !dto.getPassword().isEmpty()) {
            user.setPassword(passwordEncoder.encode(dto.getPassword()));
        }
        // 如需更新用户名，需先检查新用户名是否已存在
        user.setUsername(dto.getUsername());
        userMapper.update(user);
    }

    // 注册
    public void register(String username, String rawPwd) {
        if (userMapper.findByUsername(username) != null) {
            throw new RuntimeException("用户名已存在");

        }
        User u = new User();
        u.setUsername(username);
        u.setPassword(passwordEncoder.encode(rawPwd));
        userMapper.insert(u);
    }

    // 登录
    public User login(String username, String rawPwd) {
        User u = userMapper.findByUsername(username);
        if (u == null) {
            // 优化：统一错误提示，避免暴露用户是否存在
            throw new RuntimeException("用户名或密码错误");
        }
        if (!passwordEncoder.matches(rawPwd, u.getPassword())) {
            throw new RuntimeException("用户名或密码错误");
        }
        return u;
    }

    // 获取用户信息（修复空指针）
    public String getMainMessage(String username) {
        if (username == null || username.isEmpty()) {
            throw new RuntimeException("用户名不能为空");
        }
        User user = userMapper.findByUsername(username);
        if (user == null) {
            return String.valueOf(Response.fail("用户不存在"));
        }
        // 确保describe为null时返回空字符串，避免后续处理NPE
        return user.getDescribe() != null ? user.getDescribe() : "";
    }
}